//
//  Response+CBHandy.swift
//  Moya_Rx
//
//  Created by fst on 2019/12/26.
//  Copyright © 2019 fst. All rights reserved.
//

import Foundation
import Moya
import HandyJSON

public extension Response {

    func mapObject<T: HandyJSON>(_ type: T.Type) throws -> T {
        guard let dict = try mapJSON() as? [String:Any]  else {
            return T()
        }
        guard let object = type.deserialize(from: dict) else {
             throw MoyaError.jsonMapping(self)
        }
        return object
   }
    
    func mapArray<T: HandyJSON>(_ type: T.Type) throws -> [T] {
        guard let array = try mapJSON() as? [[String : Any]] else {
            throw MoyaError.jsonMapping(self)
        }
        var models:[T] = []
        for dict in array {
            if let model = type.deserialize(from: dict) {
                models.append(model)
            }else{
                assert(true, "转模型失败")
            }
        }
        return models
  }
}
